package ae.pcfc.etks.online.web.controller.user.internal.workflow.inbox;

/* $Id: UserPersonController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * April 13, 2011 	Neha_Chauhan 	        Created
 *
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.util.CommonUtils;
import ae.pcfc.etks.online.common.vo.PagingVO;
import ae.pcfc.etks.online.common.vo.WorkflowRequestVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.controller.user.general.person.UserPersonController;
import ae.pcfc.etks.online.web.model.JQGridJSONModel;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/**
 * Controller that handles all {@link UserPersonController}-related requests,
 * i.e.: all requests for /user/internal/workflow/inbox/*
 * 
 * @author Ismail
 */

@Controller
@RequestMapping(ViewPath.USER_INTERNAL_TRAKHEES_STAFF_INBOX)
public class InternalUserWorkflowInboxController extends BaseController{

	private UserDelegate userDelegate;

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	@RequestMapping(value = "/list.htm", method = RequestMethod.GET)
	public void list(HttpServletRequest request, HttpSession session, Model map) {
		if(session!=null && session.getAttribute(ConstantsAdmin.SUCCESS_PARAM) != null){
			request.setAttribute(ConstantsAdmin.SUCCESS_PARAM, session.getAttribute(ConstantsAdmin.SUCCESS_PARAM));
			session.removeAttribute(ConstantsAdmin.SUCCESS_PARAM);
		}
	}
	@RequestMapping(value = "/displayRequests")
	public @ResponseBody
	JQGridJSONModel displayServicesTable(HttpServletRequest request, @RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "rows", required = true) String rows,
			@RequestParam(value = "sidx", required = true) String sidx,
			@RequestParam(value = "sord", required = true, defaultValue = "desc") String sord,
			@RequestParam(value = "_search", required = false) String isSearch,
			@RequestParam(value = "searchField", required = false) String searchField,
			@RequestParam(value = "searchOper", required = false) String searchOper,
			@RequestParam(value = "searchString", required = false) String searchString,
			Locale locale) {

		List<String> requestParameterNames = Collections.list((Enumeration<String>) request.getParameterNames());

		for (String parameterName : requestParameterNames) {
			System.out.println("parameterName = " + parameterName);

		}

		System.out.println("page==" + page);
		System.out.println("rows==" + rows);
		System.out.println("sidx==" + sidx);
		System.out.println("searchField==" + searchField);
		System.out.println("searchOper==" + searchOper);
		System.out.println("searchString==" + searchString);
		System.out.println("isSearch==" + isSearch);
		System.out.println("sord==" + sord);

		JQGridJSONModel result = new JQGridJSONModel();
		String userName = request.getRemoteUser();
		if(!org.apache.commons.lang.StringUtils.isBlank(userName)){
		
		    userName = WordUtils.capitalize(userName.toLowerCase(),new char[]{'.'});
			// Temporary Fix - Code added to make sure user name is matching with one in Active directory(case sensitive)
		    final String DOT_SEPERATOR = "."; 
		    final String MIDDLE_NAME = "Al";
		    if(StringUtils.startsWith(StringUtils.substringAfter(userName,DOT_SEPERATOR), MIDDLE_NAME))		    		
		    {
		    	String tempLastName = StringUtils.substringAfter(userName,DOT_SEPERATOR);	
		    	tempLastName = MIDDLE_NAME+WordUtils.capitalize(StringUtils.substringAfter(tempLastName,MIDDLE_NAME));
		    	userName = StringUtils.substringBefore(userName,DOT_SEPERATOR)+DOT_SEPERATOR+tempLastName;
		    }
		}
		System.out.println(" 7 userName="+userName);

		List<WorkflowRequestVO> requests = this.userDelegate.getUserWorkflowRequests(userName);
		Integer pageIndx = 1, count = 0, totalpages = 0, start = 0;
		if(requests!= null){
		    count = requests.size();
		    final String sortField = sidx;
		    int sortOrder = 1;
		    if(ConstantsAdmin.DESC_ORDER.equalsIgnoreCase(sord)){
		    	sortOrder = -1;
			}
		    final int fSortOrder = sortOrder;	
			Collections.sort(requests, new Comparator<WorkflowRequestVO>() {
			    /**
			     * compare
			     * 
			     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
			     * 
			     */
			    public int compare(WorkflowRequestVO o1,WorkflowRequestVO o2) {
					int cmp = o1.getStrProcessCode().compareTo(o2.getStrProcessCode());
					if(cmp != 0){
					    return cmp;
					}else{
						if(sortField != null && sortField.contains("Id")){
					        return CommonUtils.getLongFieldValue(o1, sortField).compareTo(CommonUtils.getLongFieldValue(o2, sortField)) * fSortOrder;
						}else{
					        return CommonUtils.getStringFieldValue(o1, sortField).compareTo(CommonUtils.getStringFieldValue(o2, sortField)) * fSortOrder;
						}
				    }
			    }
			});
		}
		
		Integer limit = 40;
		try {
			pageIndx = Integer.parseInt(page);
		} catch (Exception nullexp) {
			pageIndx = 1;
		}
		try {
			limit = Integer.parseInt(rows);
		} catch (Exception nullexp) {
			pageIndx = 10;
		}

		if (count > 0)
			totalpages = (int) Math.ceil(((float) count) / (float) limit);
		else
			totalpages = 0;

		if (pageIndx > totalpages)
			pageIndx = totalpages;

		start = (limit * pageIndx) - limit;
		result.setPage(pageIndx.toString());
		result.setRecords(count + "");
		result.setTotal(totalpages + "");
		
		PagingVO pagingVO = new PagingVO();
		pagingVO.setStart(start);
		pagingVO.setSearchfieldName(searchField);
		pagingVO.setSerachString(searchString);
		pagingVO.setSortFieldName(sidx);
		pagingVO.setSortOrder(sord);
		pagingVO.setPageNumber(pageIndx);
		pagingVO.setPageSize(limit);
		

		if(requests!=null){
        		//for (WorkflowRequestVO requestVO : requests) {
		    	for(int idx = start, elmts = 0; idx < requests.size() && elmts < limit; idx++, elmts++){
		    	    WorkflowRequestVO requestVO = requests.get(idx);
		    	    if(requestVO != null){
        			List<String> cells = new ArrayList<String>();
        			cells.add(requestVO.getStrApplicationId());
        			cells.add(requestVO.getStrClientRefNo());
        			cells.add(requestVO.getStrWFIncidentId());
        			cells.add(requestVO.getStrProcessCode());
        			cells.add(requestVO.getStrProcessCodeDescAr());
        			cells.add(requestVO.getStrProcessCodeDescEn());
        			cells.add(requestVO.getStrProcessStep());
        			cells.add(requestVO.getStrProcessStepDescAr());
        			cells.add(requestVO.getStrProcessStepDescEn());
        			if(!StringUtils.isBlank(requestVO.getStrApplicationId())){
        			    cells.add(SecurityUtils.encryptQueryParam(requestVO.getStrApplicationId()));
        			}else{
        			    cells.add("");
        			}
        			if(!StringUtils.isBlank(requestVO.getStrWFIncidentId())){
        			    cells.add(SecurityUtils.encryptQueryParam(requestVO.getStrWFIncidentId()));
        			}else{
        			    cells.add("");
        			}
        			if(!StringUtils.isBlank(requestVO.getStrProcessStep())){
        			    cells.add(SecurityUtils.encryptQueryParam(requestVO.getStrProcessStep()));
        			}else{
        			    cells.add("");
        			}
        			
        			result.addRows(requestVO.getStrApplicationId()+requestVO.getStrProcessStep(), cells);
		    	    }
		    	}
        		//}
		}
		return result;
	}
}
